// pages/search-detail/index.js
import {
  getHotSearchData,
  getSearchSuggest,
  getSearchResult
} from '../../services/search-api'
import {throttle} from '../../utils/throttle'
const _getSeaerchSuggest = throttle(getSearchSuggest,500)
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hotSearch:[],
    searchSuggests:[],
    searchResults:[],
    keywords:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getHotSearchData().then(res => {
      const hotSearch = res.result.hots
      this.setData({hotSearch})
    })
    
  },
  handleSearchChange(e){
    const keywords = e.detail
    this.setData({keywords})
    if(!keywords.length) {
      _getSeaerchSuggest.cancel()
      this.setData({searchSuggests:[],searchResults:[]})
      return 
    }
    _getSeaerchSuggest(keywords).then(res => {
      const searchSuggests = res.result.allMatch
      if(!searchSuggests) return 
      this.setData({searchSuggests})
    })
  },
  handleSearch(e){
    const keywords = e.currentTarget.dataset.keywords
    this.setData({keywords})
    getSearchResult(keywords).then(res => {
      const searchResults = res.result.songs 
      this.setData({searchResults})
    })
  },
  handleSearchClick(){
    getSearchResult(this.data.keywords).then(res => {
      const searchResults = res.result.songs 
      this.setData({searchResults})
    })
  }
})